<?php
namespace app\common\service;


use app\api\controller\admin\CounselorRankController;
use think\Db;
use think\Model;

class CounselorService extends BaseService
{
    /**
     * 顾问绑定区域
     * @param $sid
     * @param $ac_id
     * @param $postParam
     * @return array
     * @throws \think\Exception
     */
    public function BlindArea($sid, $ac_id, $postParam)
    {
        //区域信息
        $ac_info = db('counselor_area_class')->where(['sid' => $sid, 'ac_id' => $ac_id])->field('path')->find();
        if (empty($ac_info)) {
            return ['status' => 0, 'msg' => '参数错误'];
        }
        $where = [
            'sid' => $sid
        ];
        $res = db('user_integral')->where($where)->whereIn('userid', $postParam['uid'])->update(['counselor_ac_path' => $ac_info['path'] . '-' . $ac_id . '-', 'counselor_ac_id' => $ac_id]);
        if ($res === false) {
            return ['status' => 0, 'msg' => '绑定失败'];
        } else {
            return ['status' => 1];
        }
    }

    /**
     * 顾问列表
     * @param $sid
     * @param int $ac_id 区域id
     * @param int $rank_id 顾问等级ID
     * @param string $search
     * @return mixed
     */
    public function GetCounselorList($sid, $ac_id = 0, $rank_id = 0, $search = '', $p = 1, $pageSize = 10)
    {
        $where = [
            'ui.sid' => $sid,
            'ui.counselor_status' => 1,
            'u.status' => 1
        ];
        //区域
        if (!empty($ac_id)) {
            $where['ui.counselor_ac_path'] = ['like', '%-' . $ac_id . '-%'];
        }
        //搜索
        if (!empty($search)) {
            $where['s.phone|u.user_nickname|s.name'] = ['like', '%' . $search . '%'];
        }
        //商务等级
        if (!empty($rank_id)) {
            $where['ui.counselor_rank_id'] = $rank_id;
            $order = 'ui.addtime desc';
        } else {
            $order = 'ui.is_ac_admin desc,ui.counselor_ac_path asc';
        }
        $list_count = db('user_integral')
            ->alias('ui')
            ->join('user u', 'u.user_id = ui.userid', 'left')
            ->join('students s', 's.uid = ui.userid', 'left')
            ->where($where)
            ->count();
        $field = 'u.user_id as uid,u.user_nickname,u.user_headimgurl,u.user_mobile,ui.sid,ui.addtime,ui.parent_id,ui.counselor_status,ui.counselor_rank_id,ui.counselor_ac_id,ui.counselor_ac_path,ui.is_ac_admin,ui.students_id,s.name,s.phone,s.company,s.formal_status';
        $list = db('user_integral')
            ->alias('ui')
            ->join('user u', 'u.user_id = ui.userid', 'left')
            ->join('students s', 's.uid = ui.userid', 'left')
            ->where($where)
            ->field($field)
            ->order($order)
            ->limit(($p - 1) * $pageSize, $pageSize)
            ->select();
        if (!empty($list)) {
            $rankServer = new CounselorRankService();
            $areaServer = new CounselorAreaClassService();
            $userServer = new UserService();
            $studentServer = new StudentService();
            foreach ($list as $k => $v) {
                //顾问手机号码
                $list[$k]['phone'] = $v['phone'] ? $v['phone'] : $v['user_mobile'];
                //商务等级
                $list[$k]['counselor_rank_name'] = $rankServer->getRankName($sid, $v['counselor_rank_id']);
                //所属区域
                $list[$k]['counselor_ac_name'] = $areaServer->GetAreaName($sid, $v['counselor_ac_id']);
                //粉丝总数
                $list[$k]['fans_num'] = $userServer->getFansCount($sid, $v['uid']);
                //意向客户总数
                $list[$k]['prospect_num'] = $studentServer->getCustomerCount($sid, $v['uid'], 0);
                //签单客户总数
                $list[$k]['customer_num'] = $studentServer->getCustomerCount($sid, $v['uid'], 1);
            }
        }

        return ['content' => $list, 'page' => ['count' => $list_count]];
    }

    /**
     * 取消顾问资格
     * @param $sid
     * @param $postParam
     * @return array
     * @throws \think\Exception
     */
    public function Recusal($sid, $postParam)
    {
        //查询当前用户是否存在粉丝或客户
        /*$children = db('user_integral')->where(['sid' => $sid, 'parent_id' => ['in', $postParam['uid']]])->count();
        if($children > 0){
            return ['status' => 0, 'msg' => '当前顾问存在粉丝或客户，请转移后再取消'];
        }

        $where = [
            'sid' => $sid
        ];
        $res = db('user_integral')
               ->where($where)
               ->whereIn('userid',$postParam['uid'])
               ->update(['counselor_status' => 0,'counselor_edittime'=>time()]);
        if($res === false){
            return ['status'=>0,'msg'=>'取消资格失败'];
        }else{
            return ['status'=>1];
        }*/
        $userService = new UserService();
        if ($postParam['uid']) {
            foreach ($postParam['uid'] as $k => $v) {
                $r = $userService->cancelCounselor($sid, $v);
                if ($r['status'] == 0) {
                    return ['status' => 0, 'msg' => '取消资格失败'];
                }
            }
            return ['status' => 1, 'msg' => '取消成功'];
        }
    }

    /**
     * 获取顾问详情
     * @param $sid
     * @param $uid
     * @return array
     */
    public function getCounselorDetail($sid, $uid)
    {
        $where = [
            'ui.userid' => $uid,
            'ui.sid' => $sid,
            'ui.counselor_status' => 1,
            'u.status' => 1
        ];
        $field = 'u.user_id as uid,u.user_nickname,u.user_headimgurl,ui.sid,ui.addtime,ui.parent_id,ui.counselor_status,ui.counselor_rank_id,ui.counselor_ac_id,ui.counselor_ac_path,ui.students_id,s.name,s.phone,s.company,s.formal_status';
        $info = db('user_integral')
            ->alias('ui')
            ->join('user u', 'u.user_id = ui.userid', 'left')
            ->join('students s', 's.uid = ui.userid', 'left')
            ->where($where)
            ->field($field)
            ->find();
        if (empty($info)) {
            return ['status' => 0, 'msg' => '参数错误'];
        }
        $rankServer = new CounselorRankService();
        $areaServer = new CounselorAreaClassService();
        $userServer = new UserService();
        $studentServer = new StudentService();
        //商务等级
        $info['counselor_rank_name'] = $rankServer->getRankName($sid, $info['counselor_rank_id']);
        //所属区域
        $info['counselor_ac_name'] = $areaServer->GetAreaName($sid, $info['counselor_ac_id']);
        //粉丝总数
        $info['fans_num'] = $userServer->getFansCount($sid, $uid);
        //意向客户总数
        $info['prospect_num'] = $studentServer->getCustomerCount($sid, $uid, 0);
        //签单客户总数
        $info['customer_num'] = $studentServer->getCustomerCount($sid, $uid, 1);
        $data = ['content' => $info];
        return ['status' => 1, 'data' => $data];
    }

    /**
     * 转移客户
     * @param $sid
     * @param $counselor_id
     * @param $postParam
     * @return array
     */
    public function TransferCustomer($sid, $counselor_id, $postParam)
    {
        /*$uids = $postParam['uid'];
        if(!is_array($uids) || count($uids) < 1){
            return ['status' => 0, 'msg' => '参数错误'];
        }

        foreach($uids as $v)
        {
            if(!$v)
            {
                return ['status' => 0, 'msg' => '参数错误,uid不能为0'];
            }
        }*/

        //将uid更改为students_id作为查询
        $students_ids = $postParam['students_ids'];
        $uids = [];

        if (!is_array($students_ids) || count($students_ids) < 1) {
            return ['status' => 0, 'msg' => '参数错误'];
        }

        foreach ($students_ids as $v) {
            if (!$v) {
                return ['status' => 0, 'msg' => '参数错误,students_id不能为0'];
            }
        }

        //设置上级顾问时，查询上级是否为顾问状态
        $counselor_status = db('user_integral')->where(['sid' => $sid, 'userid' => $counselor_id])->value('counselor_status');

        if ($counselor_status != 1) {
            return ['status' => 0, 'msg' => '不存在上级顾问'];
        }

        /*foreach($uids as $k => $uid){
            $user_info = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->field('counselor_status,parent_id')->find();
            if($user_info['counselor_status'] == 1){
                return ['status' => 0, 'msg' => '当前用户无法设置上级顾问'];
            }
            $add_data[] = [
                'sid' => $sid,
                'uid' => $uid,
                'pre_counselor_id' => $user_info['parent_id'],
                'cur_counselor_id' => $counselor_id,
                'addtime' => time()
            ];
        }*/
        foreach ($students_ids as $k => $v) {
            $user_info = db('students s')
                ->join('user_integral ui', 's.uid = ui.userid', 'LEFT')
                ->field('ui.counselor_status,s.uid,s.counselor_id')
                ->where(['s.sid' => $sid, 's.id' => $v])
                ->find();
            if ($user_info['uid']) {
                if ($user_info['counselor_status'] == 1) {
                    return ['status' => 0, 'msg' => '当前用户无法设置上级顾问'];
                }
                $uids[] = $user_info['uid'];
            }
            $add_data[] = [
                'sid' => $sid,
                'uid' => $user_info['uid'] ?? 0,
                'pre_counselor_id' => $user_info['counselor_id'],
                'cur_counselor_id' => $counselor_id,
                'addtime' => time(),
                'students_id' => $v
            ];
        }

        //$restult = db('user_integral')->where(['sid' => $sid, 'userid' => ['in', $uids]])->setField('parent_id', $counselor_id);
        $restult = true;
        if ($uids) {
            $restult = db('user_integral')->where(['sid' => $sid, 'userid' => ['in', $uids]])->update(['parent_id' => $counselor_id, 'counselor_id' => $counselor_id]);
        }
        // 更新学员表，如果是学员就可以更新到，不是也无所谓
//        db('students')->where(['sid' => $sid, 'uid' => ['in', $uids]])->update(['counselor_id'=>$counselor_id]);
        db('students')->where(['sid' => $sid, 'id' => ['in', $students_ids]])->update(['counselor_id' => $counselor_id]);

        if ($restult === false) {
            return ['status' => 0, 'msg' => '设置失败'];
        } else {
            $tplServer = new WxTplMsgService();
            foreach ($uids as $uid) {
                $tplServer->send($sid, $uid, 'user');
            }
            db('change_counselor_log')->insertAll($add_data);
            return ['status' => 1, 'msg' => '设置成功'];
        }
    }


    /**
     * 转移粉丝
     * @param $sid
     * @param $counselor_id
     * @param $postParam
     * @return array
     * @throws \think\Exception
     */
    public function TransferFans($sid, $counselor_id, $postParam)
    {
        $uids = $postParam['uids'];
        if (!is_array($uids) || count($uids) < 1) {
            return ['status' => 0, 'msg' => '参数错误'];
        }

        foreach ($uids as $v) {
            if (!$v) {
                return ['status' => 0, 'msg' => '参数错误,uid不能为0'];
            }
        }

        //设置上级顾问时，查询上级是否为顾问状态
        $counselor_status = db('user_integral')->where(['sid' => $sid, 'userid' => $counselor_id])->value('counselor_status');

        if ($counselor_status != 1) {
            return ['status' => 0, 'msg' => '不存在上级顾问'];
        }

        foreach ($uids as $k => $uid) {
            $user_info = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->field('counselor_status,parent_id')->find();
            if ($user_info['counselor_status'] == 1) {
                return ['status' => 0, 'msg' => '当前用户无法设置上级顾问'];
            }
            $add_data[] = [
                'sid' => $sid,
                'uid' => $uid,
                'pre_counselor_id' => $user_info['parent_id'],
                'cur_counselor_id' => $counselor_id,
                'addtime' => time(),
                'students_id' => 0
            ];
        }

        $restult = db('user_integral')->where(['sid' => $sid, 'userid' => ['in', $uids]])->update(['parent_id' => $counselor_id, 'counselor_id' => $counselor_id]);

        if ($restult === false) {
            return ['status' => 0, 'msg' => '设置失败'];
        } else {
            $tplServer = new WxTplMsgService();
            foreach ($uids as $uid) {
                $tplServer->send($sid, $uid, 'user');
            }
            db('change_counselor_log')->insertAll($add_data);
            return ['status' => 1, 'msg' => '设置成功'];
        }
    }


    /**
     * 获取顾问名片风格列表
     * @param $sid
     * @return array
     */
    public function getCounselorCardStyle($sid)
    {
//        $list = db('counselor_card')->where(['sid' => $sid])->order('style_id ASC')->select();
        //店铺模版更改为系统模板
        $list = db('counselor_card')->order('style_id ASC')->select();
        if ($list) {
            foreach ($list as $k => $v) {
                $list[$k]['card_bg_thumb'] = 'http://' . request()->server('HTTP_HOST') . $v['card_bg_thumb'];
            }
        }
        return ['content' => $list];
    }

    /**
     * 选择顾问名片风格
     * @param $sid
     * @param $counselor_card_id
     * @return int
     */
    public function setCounselorCard($sid, $counselor_card_id)
    {
//        $info = db('counselor_card')->where(['sid' => $sid, 'id' => $counselor_card_id])->find();
        $info = db('counselor_card')->where(['id' => $counselor_card_id])->find();
        if (empty($info)) {
            return ['status' => 0, 'msg' => '不存在此风格'];
        }
        if ($info['is_using'] == 1) {
            return ['status' => 0, 'msg' => '当前风格已处于使用状态'];
        }
//        db('counselor_card')->where(['sid' => $sid, 'is_using' => 1])->setField('is_using', 0);
//        $result = db('counselor_card')->where(['sid' => $sid, 'id' => $counselor_card_id])->setField('is_using', 1);
        db('counselor_card')->where(['is_using' => 1])->setField('is_using', 0);
        $result = db('counselor_card')->where(['id' => $counselor_card_id])->setField('is_using', 1);
        if ($result) {
            return ['status' => 1, 'msg' => '选择成功'];
        } else {
            return ['status' => 0, 'msg' => '选择失败'];
        }
    }


    /**
     * 微信端: 获取顾问可发送优惠券的用户列表
     * @param $sid
     * @param $uid
     * @param $search
     * @param $p
     * @param $pageSize
     * @return mixed
     */
    public function getCouponUserList($sid, $uid, $search, $p, $pageSize)
    {
        $field = 'u.user_id,u.user_nickname,u.user_headimgurl,s.id as student_id,s.name,s.phone';
        $where = [
            'ui.userid' => ['<>', $uid],
            'ui.counselor_status' => 0,
            'ui.parent_id|ui.counselor_id|s.counselor_id' => $uid,
            'ui.sid' => $sid,
            'u.user_nickname|s.name|s.phone' => ["like", "%$search%"]
        ];
        $list = db('user_integral ui')
                ->field($field)
                ->join('user u', 'u.user_id=ui.userid')
                ->join('students s', 'ui.userid=s.uid', 'LEFT')
                ->where($where)
                ->limit(($p - 1)*$pageSize, $pageSize)
                ->order('u.create_time DESC')
                ->select();
        return $list;
    }

    /**
     * 微信端: 顾问发送优惠券
     * @param $sid
     * @param $uid
     * @param $present_uids
     * @param $coupon_id
     * @return array
     */
    public function presentCoupon($sid, $uid, $present_uids, $coupon_id)
    {
        if(empty($present_uids)){
            return ['status' => 0, 'msg' => '请选择发送对象'];
        }

        // 已经领取过的用户ID
        $own_coupon_uids = db('user_coupon')
            ->where([
                'sid' => $sid,
                'coupon_id' => $coupon_id,
                'uid' => ['in', $present_uids]
            ])
            ->column('uid');

        // 未领取的用户ID
        $user_ids = array_unique(array_diff($present_uids, array_unique($own_coupon_uids)));
        if(empty($user_ids)){
            return ['status' => 0, 'msg' => '您已赠送过啦'];
        }

        // 优惠券是否有效
        $coupon_where = [
            'sid' => $sid,
            'coupon_id' => $coupon_id,
            'coupon_end' => ['>', time()],
            'status' => 1
        ];
        $coupon = db('coupon')->where($coupon_where)->find();
        if(empty($coupon)){
            return ['status' => 0, 'msg' => '该优惠券不存在或已失效'];
        }
        // 库存判断
        if($coupon['surplus'] < count($user_ids)){
            return ['status' => 0, 'msg' => '优惠券余量不足'];
        }

        $user_coupon_data = [];
        foreach($user_ids as $k => $v){
            $user_coupon_data[$k]['uid'] = $v;
            $user_coupon_data[$k]['sid'] = $sid;
            $user_coupon_data[$k]['coupon_id'] = $coupon_id;
            $user_coupon_data[$k]['is_counselor_appoint'] = 1;
            $user_coupon_data[$k]['presenter_uid'] = $uid;
            $user_coupon_data[$k]['add_time'] = time();
        }
        Db::startTrans();
        try{
            db('user_coupon')->insertAll($user_coupon_data);
            $r = db('coupon')->where('coupon_id', $coupon_id)->setInc('receive', count($user_ids));
            db('coupon')->where('coupon_id', $coupon_id)->setDec('surplus', count($user_ids));
            Db::commit();
        } catch(\Exception $e){
            Db::rollback();
            return ['status' => 0, 'msg' => '发送失败'];
        }

        // 发送模版消息
        $wxTplMsgService = new WxTplMsgService();
        foreach($user_ids as $key => $val){
            $wxTplMsgService->send($sid, $val, 'coupon_present', $coupon);
        }

        return ['status' => 1, 'msg' => '发送成功'];
    }

}